package com.servicesystem.servicesystem.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.servicesystem.servicesystem.entity.UserAli;
import com.servicesystem.servicesystem.service.UserAliService;
import com.servicesystem.servicesystem.untis.token.GenerateTokenUtils;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

public class BeforeLoginFilter extends OncePerRequestFilter {
    private final GenerateTokenUtils generateTokenUtils;
    private final UserAliService userAliService;

    public BeforeLoginFilter(GenerateTokenUtils generateTokenUtils, AuthenticationManager authenticationManager, UserAliService userAliService) {
        this.generateTokenUtils = generateTokenUtils;
        this.userAliService = userAliService;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = resolveToken(request);
        if (StringUtils.hasText(token) && GenerateTokenUtils.validateToken(token)) {
            ArrayList<GrantedAuthority> authorities = new ArrayList<>();
            authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
            String username = generateTokenUtils.parseToken(token);
            if (username != null) {
                QueryWrapper<UserAli> userAliQueryWrapper = new QueryWrapper<>();
                userAliQueryWrapper.eq("username", username);
                UserAli userAli = userAliService.getOne(userAliQueryWrapper);
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                        userAli.getUsername(),
                        "root", authorities);
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }
        filterChain.doFilter(request, response);
    }

    private String resolveToken(HttpServletRequest request) {
        String bearerToken = request.getHeader("token");
        if (StringUtils.hasText(bearerToken)) {
            return bearerToken;
        }
        return null;
    }
}
